/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/


import { sceneDetail } from '@/services/httpService';
import { Reducer } from 'redux';
export interface RootState {
  status: any;
  vm: any;
  global: GlobalModelState;
}

export interface GlobalModelState {
  skillJson: any[];
  skillMap: object;
  blockJson: string;
  isLoading: boolean;
  loadingList: {
    loading: false;
    apiName: string;
  }[];
  sceneUuid: string;
  name: string;
  modalMsg: string;
  modalOk: any;
  modalDisabled: boolean;
  projectChanged: boolean;
  editerRules: any;
  sceneJson: any;
  fileMap: Map<string, string>;
  markBlocksMap: Map<string, number[]>;
}

export interface GlobalModelType {
  namespace: 'editGlobal';
  state: GlobalModelState;
  effects: {
    setModalConfirm: any;
    getSceneJson: any;
    setLoading: any;
  };
  reducers: {
    setGlobalState: Reducer<GlobalModelState>;
    resetGlobalState: Reducer<GlobalModelState>;
  };
}

const getInitState = (): GlobalModelState => {
  return {
    skillJson: [], // 能力json
    skillMap: {},
    isLoading: false, // 全局loading状态
    loadingList: [], // 新增一个 loadingList 数组来存储接口的 loading 状态和接口名
    blockJson: '', // 场景数据
    sceneUuid: '', // 场景id
    name: '', // 场景名称
    modalMsg: '',
    modalOk: null,
    modalDisabled: true,
    projectChanged: false,
    editerRules: {}, // 存储竞合关系
    sceneJson: {}, // 场景json数据
    fileMap: new Map([]), // 文件map
    markBlocksMap: new Map([]), // 标记map
  };
};

const EditModel: GlobalModelType = {
  namespace: 'editGlobal',
  state: getInitState(),
  effects: {
    // modal confirm 提示函数 传入一个 msg
    setModalConfirm: function* ({ payload }, { put }) {
      const { msg, okCb } = payload;
      yield put({
        type: 'setGlobalState',
        payload: {
          modalMsg: msg,
          modalOk: okCb,
          modalDisabled: false,
        },
      });
    },

    // 获取场景json
    getSceneJson: function* ({ payload }, { put }) {
      try {
        const { sceneUuid, modelCode, seriesCode } = payload;
        const {
          data: sceneJson,
          statusCode,
          statusMessage,
        } = yield sceneDetail({ sceneUuid, modelCode, seriesCode });

        yield put({
          type: 'setGlobalState',
          payload: {
            sceneJson,
          },
        });

        return {
          statusCode,
          sceneJson,
          statusMessage,
        };
      } catch (error) {
        console.log('🚀 ~ file: editGlobal.ts ~ line 108 ~ error', error);
      }
    },

    // 控制loading
    setLoading: function* ({ payload }, { put, select }) {
      try {
        // 获取当前的 loadingList 数组
        const { loadingList } = yield select((state) => state.editGlobal);

        // 从 payload 中获取 loading 和 apiName
        const { loading, apiName } = payload;
        // console.log('🚀 ~ file: editGlobal.ts ~ line 120 ~ loading, apiName', loading, apiName);

        // 克隆 loadingList 数组，以便后续操作不会影响原数组
        let newLoadingList = [...loadingList];

        if (loading) {
          // 添加接口名和 loading 状态到数组中
          newLoadingList.push({ apiName, loading });
        } else {
          // 删除对应接口名的对象
          newLoadingList = newLoadingList.filter((item) => item.apiName !== apiName);
        }

        // 根据新的 loadingList 数组是否为空来判断是否显示全局 loading
        const isLoading = newLoadingList.length > 0;

        // 在一个 'put' 调用中同时更新 'loadingList' 和 'isLoading' 的状态
        yield put({
          type: 'setGlobalState',
          payload: {
            loadingList: newLoadingList,
            isLoading,
          },
        });
      } catch (error) {
        // 如果有错误，可以在这里处理
        console.error(error);
      }
    },
  },
  reducers: {
    setGlobalState(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    resetGlobalState(state, action) {
      return {
        ...state,
        ...getInitState(),
        ...action.payload,
      };
    },
  },
};

export default EditModel;
